package com.chen.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.chen.common.Result;
import com.chen.entity.bean.FastDFSFile;
import com.chen.service.impl.UserServiceImpl;
import com.chen.utils.FastDFSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 文件上传下载
 *
 * @author chenchao
 * @date 2022/7/29 21:10
 */
@RestController
@RequestMapping("/file")
@Api(value="FileController",tags = "文件管理")
public class FileController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Value("${server.ip}")
    private String serverIp;

    @Value("${server.port}")
    private String port;


    private static Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);

    @Resource
    private UserServiceImpl userService;

    /**
     * 文件上传接口
     * @param file 前端传递过来的文件
     * @return
     * @throws IOException
     */

    @ApiOperation(value = "头像上传")
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        // 定义一个文件唯一的标识码
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        File parentFile = uploadFile.getParentFile();
        if(!parentFile.exists()) {
            parentFile.mkdirs();
        }
        String url;
        // 获取文件的md5
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件，则不删除刚才上传的文件
                url = "http://" + serverIp + ":"+port+"/file/" + fileUUID;

        return url;
    }
    /**
     * 文件下载接口   http://localhost:9090/file/{fileUUID}
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }





//    @PostMapping("/upload")
//    public String FileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
//        if (file.isEmpty()) {
//            redirectAttributes.addFlashAttribute("message", "请选择一个文件上传");
//
//            return "redirect:uploadStatus";
//        }
//        try {
//            String path = saveFile(file);
//            redirectAttributes.addFlashAttribute("message", "上传成功" + file.getOriginalFilename());
//            redirectAttributes.addFlashAttribute("path", "路径" + path);
//
//        } catch (IOException e) {
//            logger.error("上传失败" + e);
//        }
//
//        return "redirect:uploadStatus";
//    }


    public String saveFile(MultipartFile file) throws Exception {
        String[] fileAbsoultePath = {};
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("." + 1));
        byte[] file_buff = null;
        InputStream inputStream = file.getInputStream();
        if (inputStream != null) {
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);

        }
        inputStream.close();
        FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, file_buff, ext);
        fileAbsoultePath = FastDFSUtil.upload(fastDFSFile);
        if (fileAbsoultePath == null) {
            logger.error("上传失败");
        }

        String path = FastDFSUtil.getTrackerUrl() + fileAbsoultePath[0] + "/" + fileAbsoultePath[1];
        return path;
    }


    @ApiOperation(value = "上传")
    @PostMapping("/upload1")
    public Result updateUserFace(MultipartFile file) throws Exception {
        String[] filePath = FastDFSUtil.upload(file);
        String url = FastDFSUtil.getTrackerUrl() + filePath[0] + "/" + filePath[1];

        return Result.success(url);
    }



    @PostMapping("/editor/load")
    public JSON editorUpload(@RequestParam MultipartFile file) throws IOException {  //接受前台的对象
        //定义文件唯一标识
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        // 定义一个文件唯一的标识码
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        File parentFile = uploadFile.getParentFile();
        if(!parentFile.exists()) {
            parentFile.mkdirs();
        }
        String url;
        // 获取文件的md5
        // 上传文件到磁盘
        file.transferTo(uploadFile);
        // 数据库若不存在重复文件，则不删除刚才上传的文件
        url = "http://" + serverIp + ":"+port+"/file/" + fileUUID;

        JSONObject json = new JSONObject();
        json.set("errno", 0);
//        JSONArray arr = new JSONArray();
        JSONObject data = new JSONObject();
//        arr.add(data);
        data.set("url", url);

        json.set("data", data);
        return json;
    }
}
